﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Build.Utilities;
using Microsoft.Build.Framework;
using Microsoft.SharePoint.Administration;
using System.Collections.ObjectModel;

namespace MicroLink.StsDev2008AddIn.BuildTasks
{
    public class RetractSolution : Task
    {
        #region SolutionName
        [Required()]
        public string SolutionName
        {
            get;
            set;
        }
        #endregion

        public override bool Execute()
        {
            try
            {
                SPSolution solution = SPFarm.Local.Solutions[SolutionName];
                if (solution != null)
                {
                    if (!solution.Deployed)
                    {
                        Log.LogMessage("{0} is not deployed", SolutionName);
                        return true;
                    }
                    else
                    {
                        if (solution.ContainsWebApplicationResource)
                        {
                            Collection<SPWebApplication> collection = new Collection<SPWebApplication>();
                            foreach (SPWebApplication spWebApp in solution.DeployedWebApplications)
                            {
                                collection.Add(spWebApp);
                            }
                            solution.Retract(DateTime.Now, collection);
                        }
                        else
                        {
                            solution.Retract(DateTime.Now);
                        }
                        return true;
                    }
                }
                else
                {
                    Log.LogMessage("{0} does not exist in the solution store.", SolutionName);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Log.LogError("{0}", ex.Message);
                return false;
            }
        }
    }
}
